package com.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.VO.PokemUserItemVO;
import com.VO.PokemonStoreVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.entity.*;
import com.service.*;
import com.yscredit.ys.common.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 前端控制器
 *
 * @author LiYuan
 * @since 2021-11-03
 */
@RestController
@RequestMapping("item")
public class PokemItemController {
  @Autowired private IPokemonUserItemService pokemonUserItemService;
  @Autowired private IPokemItemService pokemItemService;
  @Autowired private IPokemonUserDpService pokemonUserDpService;
  @Autowired private IPokemonStoreService pokemonStoreService;
  @Autowired private ITalkPokemonUserService talkPokemonUserService;
  @Autowired private ITalkPokemonService talkPokemonService;
  @Autowired private ITalkBallUserService talkBallUserService;
  @Autowired private IUserCishuService userCishuService;
    @Autowired private ISkillOriginService skillOriginService;
    @Autowired private IPokemonUserSkillService userSkillService;

  // 背包里道具列表
  @RequestMapping("findUserItemList")
  public ResponseMessage findUserItemList(Integer userId) {

    List<PokemonUserItem> pokemonUserItemList =
        pokemonUserItemService.list(
            new LambdaQueryWrapper<PokemonUserItem>().eq(PokemonUserItem::getUserId, userId));
    List<PokemItem> pokemItemList = pokemItemService.list();
    List<PokemUserItemVO> pokemUserItemVOS =
        pokemonUserItemList.stream()
            .map(
                s -> {
                  PokemUserItemVO pokemUserItemVO = new PokemUserItemVO();
                  BeanUtils.copyProperties(s, pokemUserItemVO);
                  pokemItemList.forEach(
                      l -> {
                        if (l.getId() == s.getItemId()) {
                          pokemUserItemVO.setItemName(l.getItemName());
                          pokemUserItemVO.setRemark(l.getRemark());
                          pokemUserItemVO.setImg(l.getImg());
                        }
                      });
                  return pokemUserItemVO;
                })
            .collect(Collectors.toList());
    return new ResponseMessage(ResponseMessage.SUCCESS, "成功", pokemUserItemVOS);
  }

  // 商城道具列表
  @RequestMapping("findStoreItemList")
  public ResponseMessage findStoreItemList() {
    List<PokemonStore> pokemonStoreList = pokemonStoreService.list();
    List<PokemItem> pokemItemList = pokemItemService.list();
    Stream<PokemonStoreVO> pokemonStoreVOStream =
        pokemonStoreList.stream()
            .map(
                s -> {
                  PokemonStoreVO pokemonStoreVO = new PokemonStoreVO();
                  BeanUtils.copyProperties(s, pokemonStoreVO);
                  pokemItemList.forEach(
                      l -> {
                        if (l.getId() == s.getItemId()) {
                          pokemonStoreVO.setImg(l.getImg());
                          pokemonStoreVO.setItemName(l.getItemName());
                          pokemonStoreVO.setRemark(l.getRemark());
                        }
                      });
                  return pokemonStoreVO;
                });

    return new ResponseMessage(ResponseMessage.SUCCESS, "成功", pokemonStoreVOStream);
  }

  // 返回用户拥有的DP货币
  @RequestMapping("findUserDP")
  public ResponseMessage findUSerDP(Integer userId) {
    PokemonUserDp one =
        pokemonUserDpService.getOne(
            new LambdaQueryWrapper<PokemonUserDp>().eq(PokemonUserDp::getUserId, userId));
    if(one==null){
        PokemonUserDp onee=new PokemonUserDp();
        onee.setDp(0);
    }
    return new ResponseMessage(ResponseMessage.SUCCESS, "成功", one);
  }

  // 购买道具
  @RequestMapping("buyItem")
  @Transactional
  public ResponseMessage buyItem(Integer userId, Integer itemId, Integer num) {

    // 根据userId获取货币
    PokemonUserDp pokemonUserDp =
        pokemonUserDpService.getOne(
            new LambdaQueryWrapper<PokemonUserDp>().eq(PokemonUserDp::getUserId, userId));
    Integer dpNum = pokemonUserDp.getDp();
    // 根据itemId获取价格
    PokemonStore pokemonStore =
        pokemonStoreService.getOne(
            new LambdaQueryWrapper<PokemonStore>().eq(PokemonStore::getItemId, itemId));
    Integer price = pokemonStore.getPrice();
    if(itemId==4){
        UpdateWrapper wrapper=new UpdateWrapper();
        wrapper.setSql("ball_num=ball_num+"+num);
        wrapper.eq("user_id",userId);
        talkBallUserService.update(wrapper);
    }
    else if (itemId==5){
       UpdateWrapper wrapper=new UpdateWrapper();
       wrapper.setSql("cishu=cishu+"+num*10);
       wrapper.eq("user_id",userId);
       userCishuService.update(wrapper);
    } else{
          // 获取背包已存在的道具
          List<PokemonUserItem> pokemonUserItems =
                  pokemonUserItemService.list(
                          new LambdaQueryWrapper<PokemonUserItem>().eq(PokemonUserItem::getItemId, itemId).eq(PokemonUserItem::getUserId,userId));

          if (pokemonUserItems.size() > 0) {
              UpdateWrapper<PokemonUserItem> wrapper2 = new UpdateWrapper<>();
              String sql = "num =num +" + num;
              wrapper2.setSql(sql).eq("item_id", itemId).eq("user_id", userId);
              pokemonUserItemService.update(wrapper2);
          } else {
              PokemonUserItem pokemonUserItem = new PokemonUserItem();
              pokemonUserItem.setItemId(itemId);
              pokemonUserItem.setUserId(userId);
              pokemonUserItem.setNum(num);
              pokemonUserItemService.save(pokemonUserItem);
          }
      }


    dpNum = dpNum - price * num;
    UpdateWrapper<PokemonUserDp> wrapper = new UpdateWrapper<>();
    wrapper.set("dp", dpNum).eq("user_id", userId);
    pokemonUserDpService.update(wrapper);

    return new ResponseMessage(ResponseMessage.SUCCESS, "成功", true);
  }

  // 使用道具
  @RequestMapping("useItem")
  public ResponseMessage useItem(Integer userId, Integer itemId,Integer id,Integer num) {
     int flag=0;
    PokemonUserItem pokemonUserItemOne =
        pokemonUserItemService.getOne(
            new LambdaQueryWrapper<PokemonUserItem>()
                .eq(PokemonUserItem::getItemId, itemId)
                .eq(PokemonUserItem::getUserId, userId));

    if(pokemonUserItemOne.getNum()<=0){
        return new ResponseMessage(ResponseMessage.FAIL,"道具数量不足哇");
    }
      TalkPokemonUser userPokemonOne = talkPokemonUserService.getOne(new LambdaQueryWrapper<TalkPokemonUser>().eq(TalkPokemonUser::getId, id));
      Integer jinhua=null;
      TalkPokemon pokemonOne = talkPokemonService.getOne(new LambdaQueryWrapper<TalkPokemon>().eq(TalkPokemon::getId, userPokemonOne.getPokemonId()));
      if(pokemonOne.getJinhuadengji()==1000){
          jinhua=1000;
      }else if (pokemonOne.getJinhuadengji()==3000){
          jinhua=3000;
      }
      Integer itemIdToUse = pokemonUserItemOne.getItemId();
      //判断使用的是什么道具，具体效果都不一样
      switch (itemIdToUse){
          case 1://神奇糖果LV1 升一级
              for (int i=0;i<num;i++){
                  levelUp(userPokemonOne);
              }

             if (jinhua!=null&&userPokemonOne.getLevel()>=jinhua){
                 jinhuaUp(userPokemonOne,jinhua);
                 jinhuahenshin(userPokemonOne,pokemonOne);
             }
             break;
          case 2://神奇糖果LV2 升10级
              for(int j=0;j<num;j++){
                  for (int i=0;i<10;i++){
                      levelUp(userPokemonOne);
                  }
              }

              if (jinhua!=null&&userPokemonOne.getLevel()>=jinhua){
                  jinhuaUp(userPokemonOne,jinhua);
                  jinhuahenshin(userPokemonOne,pokemonOne);
              }
              break;
          case 3://神奇糖果LV3 升100级
              for(int j=0;j<num;j++){
                  for (int i=0;i<100;i++){
                      levelUp(userPokemonOne);
                  }
              }

              if (jinhua!=null&&userPokemonOne.getLevel()>=jinhua){
                  jinhuaUp(userPokemonOne,jinhua);
                  jinhuahenshin(userPokemonOne,pokemonOne);
              }
              break;
          case 6://绝对零度学习书
              try{
                  String requestUrl =
                          "http://localhost:8089" + "/chatroom/skill/learnSkill" + "?userId=" + userId
                                  + "&skId=" + 8+"&pokemonId="+id;
                  String res = HttpClientUtil.get(requestUrl);
                  JSONObject jsonObject = JSONUtil.parseObj(res);
                  if (!jsonObject.get("code").toString().equals("200")){
                      return new ResponseMessage(ResponseMessage.FAIL,jsonObject.get("msg").toString());
                  }
              }catch (Exception e){
                  e.printStackTrace();
              }
            break;


          default: flag=1;

      }

      if (flag==1){
          return new ResponseMessage(ResponseMessage.FAIL,"道具使用失败");
      }else{
          UpdateWrapper wrapper2=new UpdateWrapper();
          wrapper2.eq("id",userPokemonOne.getId());
          talkPokemonUserService.update(userPokemonOne,wrapper2);
         pokemonUserItemOne.setNum(pokemonUserItemOne.getNum()-num);
         UpdateWrapper wrapper=new UpdateWrapper();
         wrapper.eq("item_id",itemId);
         wrapper.eq("user_id",userId);
          boolean update = pokemonUserItemService.update(pokemonUserItemOne, wrapper);
          return new ResponseMessage(ResponseMessage.SUCCESS,"成功",update);
      }
  }
  //升级加属性
    public void levelUp(TalkPokemonUser userPokemonOne){
        userPokemonOne.setLevel(userPokemonOne.getLevel()+1);
        userPokemonOne.setAtk(userPokemonOne.getAtk()+(int)(Math.random()*31));
        userPokemonOne.setDef(userPokemonOne.getDef()+(int)(Math.random()*31));
        userPokemonOne.setHp(userPokemonOne.getHp()+(int)(Math.random()*31));
        userPokemonOne.setSatk(userPokemonOne.getSatk()+(int)(Math.random()*31));
        userPokemonOne.setSdef(userPokemonOne.getSdef()+(int)(Math.random()*31));
        userPokemonOne.setSpe(userPokemonOne.getSpe()+(int)(Math.random()*31));
    }

    //进化加属性
    public void jinhuaUp(TalkPokemonUser userPokemonOne,Integer jinhua){
        userPokemonOne.setLevel(userPokemonOne.getLevel()+1);
        userPokemonOne.setAtk(userPokemonOne.getAtk()+jinhua);
        userPokemonOne.setDef(userPokemonOne.getDef()+jinhua);
        userPokemonOne.setHp(userPokemonOne.getHp()+jinhua);
        userPokemonOne.setSatk(userPokemonOne.getSatk()+jinhua);
        userPokemonOne.setSdef(userPokemonOne.getSdef()+jinhua);
        userPokemonOne.setSpe(userPokemonOne.getSpe()+jinhua);
    }
    //进化变身
    public void jinhuahenshin(TalkPokemonUser userPokemonOne,TalkPokemon pokemonOne){

        TalkPokemon jinhuaOne = talkPokemonService.getOne(new LambdaQueryWrapper<TalkPokemon>().eq(TalkPokemon::getId, pokemonOne.getJinhuaid()));
        userPokemonOne.setPokemonId(jinhuaOne.getId());
        userPokemonOne.setName(jinhuaOne.getName());
        userPokemonOne.setImg(jinhuaOne.getImg());
        if (jinhuaOne.getShuxin()!=null){
            userPokemonOne.setShuxin(jinhuaOne.getShuxin());
        }
        if(jinhuaOne.getShuxintwo()!=null){
            userPokemonOne.setShuxintwo(jinhuaOne.getShuxintwo());
        }

    }


}
